import { GetRolesFnc, SaveRolesFnc } from '@/services/users';
import { ModalForm, ProFormSelect } from '@ant-design/pro-components';
import { message } from 'antd';
import { useState } from 'react';
import { itemType } from './type';

const GiveRole = ({
  roleModalOpen,
  openRoleBox,
  roleName,
  roleDesc,
  openID,
  actionRef,
}: itemType) => {
  const [selectOptions, setSelectOptions] = useState<any>([]); // selectOption 选项
  const [value, setValue] = useState('');
  const [messageApi, contextHolder] = message.useMessage();

  // slect获得焦点的时候 才去获取数据
  const getFocus = async () => {
    const res = await GetRolesFnc();
    if (res.meta.status === 200) {
      let options = res.data.map((item: { id: number; roleName: string }) => {
        return {
          id: item.id,
          label: item.roleName,
          value: item.roleName,
        };
      });
      setSelectOptions(options);
    }
  };

  // 保存角色
  const onFinish = async () => {
    const res = await SaveRolesFnc(parseInt(openID), {
      rid: selectOptions[0].id,
    });
    if (res.meta.status === 200) {
      messageApi.success('更新成功', 1.5, () => {
        openRoleBox(false);
        actionRef.current?.reload();
        setValue('');
      });
    }
  };

  return (
    <>
      {contextHolder}
      <ModalForm
        title="分配用户"
        width={500}
        layout="horizontal"
        labelCol={{ span: 4 }}
        open={roleModalOpen}
        onFinish={onFinish}
        modalProps={{ onCancel: () => openRoleBox(false) }}
      >
        <p>当前的用户: {roleName}</p>
        <p style={{ margin: '20px 0' }}>当前的角色: {roleDesc}</p>
        <span>分配角色 </span>
        <ProFormSelect
          options={selectOptions}
          placeholder="请选择"
          fieldProps={{
            value: value,
            onFocus: getFocus,
            onChange: (value: string) => setValue(value),
          }}
        />
      </ModalForm>
    </>
  );
};

export default GiveRole;
